import router from '@/router'
import store from '@/store'
import {Toast,Dialog } from 'vant'
import {getToken} from '@/utils/auth'
import {hiddeList} from '@/router/modules/TabBar.js'
const whiteList = ['/login','/home','/about']

router.beforeEach(async(to,from,next)=>{
  //页面title
  store.state.user.title =  to.meta.title

  //判断左上角返回Icon是否显示
  store.state.user.leftIconIsShow = hiddeList.includes(to.path)

  //1.判断用户是否已经登陆
  const hashToken = getToken()
  if(hashToken){
    if(to.path === '/login'){
      next({path:'/'})
    }else{
      //判断用户是否获取了用户信息并进行了权限判断
      const roles = store.getters.userInfo.roles&&store.getters.userInfo.roles.length>0;
      if(roles){
        next()
      }else{
        try {

           // 注意：角色必须是对象数组！ 例如：['admin']或，['developer'，'editor']
          //  const { roles } = await store.dispatch('user/getInfo')

          //  // 根据角色生成可访问的路线图
          //  const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
 
          //  // 动态添加可访问的路线
          //  router.addRoutes(accessRoutes)

          // hack方法，以确保addRoutes是完整的
          // 设置replace：true，因此导航将不会留下历史记录
          next({ ...to, replace: true })
        } catch (error) {
          //否则删除token重新登陆
          Toast('你的身份信息有误，清重新登陆')
          await store.dispatch('user/resetToken')
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  }else{
    //未登录，进入白名单判断
    if(whiteList.indexOf(to.path) !== -1){
      next()
    }else{
      Dialog({message:'请登录'})
      next({path:'/home'})
    }
  }

})

